import { App, DirectiveBinding } from "vue";
export default (app: App<Element>) => {
  app.directive("btnAntiShake", {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
      let timer: NodeJS.Timeout | null = null;
      el.addEventListener("click", () => {
        let firstClick: Boolean = !timer;
        if (firstClick) {
          binding.value();
        }
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          timer = null;
          if (!firstClick) {
            binding.value();
          }
        }, 1000);
      });
    },
  });
};

// 格式化日期
interface IDateFormatKeyConfig {
  YYYY: string;
  MM: string;
  DD: string;
  HH: string;
  mm: string;
  ss: string;
  [index: string]: string;
}
export function formateDate(
  val: string | null,
  format = "YYYY-MM-DD HH:mm:ss"
) {
  function incZero(val: number): string {
    return val < 10 ? "0" + val : val + "";
  }
  if (!val) return "";
  let date = new Date(val);
  const config: IDateFormatKeyConfig = {
    YYYY: incZero(date.getFullYear()),
    MM: incZero(date.getMonth() + 1),
    DD: incZero(date.getDate()),
    HH: incZero(date.getHours()),
    mm: incZero(date.getMinutes()),
    ss: incZero(date.getSeconds()),
  };
  for (const key in config) {
    format = format.replace(key, config[key]);
  }
  return format;
}

